﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace XiaofangExamFramework
{
    public class ClipboardHelper2
    {
        private const int WM_COPY = 0x0301;
        private const int WM_GETTEXTLENGTH = 0x000E;
        private const int WM_GETTEXT = 0x000D;

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetForegroundWindow();

        public static string GetSelectedText()
        {
            IntPtr handle = GetForegroundWindow(); // 获取当前活动窗口句柄

            if (handle != IntPtr.Zero)
            {
                int length = (int)SendMessage(handle, WM_GETTEXTLENGTH, IntPtr.Zero, IntPtr.Zero);
                if (length > 0)
                {
                    IntPtr buffer = Marshal.AllocCoTaskMem((length + 1) * 2);
                    SendMessage(handle, WM_GETTEXT, (IntPtr)(length + 1), buffer);

                    string selectedText = Marshal.PtrToStringUni(buffer);
                    Marshal.FreeCoTaskMem(buffer);

                    return selectedText;
                }
            }

            return string.Empty;
        }

        public static void CopySelectedText()
        {
            string selectedText = GetSelectedText();

            if (!string.IsNullOrEmpty(selectedText))
            {
                Clipboard.SetText(selectedText); // 将选中的文本复制到剪贴板
            }
        }
    }
}
